package org.jeecg.modules.api.smsApi.controller;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.api.smsApi.vo.SmsSendParam;
import org.jeecg.modules.api.smsApi.vo.SmsSendRtn;
import org.jeecg.modules.sms.sms.param.SmsParam;
import org.jeecg.modules.sms.sms.service.ISmsService;
import org.jeecg.modules.sms.sms.vo.SmsRtn;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 短信服务API
 */
@RestController
@RequestMapping(CommonConstant.API+"/sms")
@Slf4j
public class SmsApiController {

    @Autowired
    ISmsService smsService;

    /**
     * 单条发送
     * @param param
     * @param bindingResult
     * @return
     */
    @AutoLog(value = "短信发送")
    @PostMapping(value = "/send")
    public Result<SmsSendRtn> send(@RequestBody @Valid SmsSendParam param, BindingResult bindingResult) {
        StringBuilder errMsg = new StringBuilder();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String defaultMessage = objectError.getDefaultMessage();
                errMsg.append(defaultMessage).append(",");
            }
        }
        if(errMsg.length() > 0){
            return Result.error(errMsg.toString());
        }
        SmsParam smsParam = new SmsParam();
        BeanUtils.copyProperties(param,smsParam);
        Result<SmsRtn> result = smsService.sendBatch(smsParam);

        if(result.isSuccess()) {
            SmsSendRtn smsSendRtn= new SmsSendRtn();
            SmsRtn smsRtns = result.getResult();
            List<SmsRtn.Fsjg> fsjgList = smsRtns.getFsjg();
            if(fsjgList != null && fsjgList.size()>0){
                SmsRtn.Fsjg fsjg = fsjgList.get(0);
                BeanUtils.copyProperties(fsjg, smsSendRtn);
            }
            return Result.OK("成功",smsSendRtn);
        } else {
            return Result.error(result.getMessage());
        }
    }
}
